package me.caofeng.service;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.sun.org.apache.regexp.internal.RE;
import me.caofeng.dao.CategoryMapper;
import me.caofeng.enums.ItemStatus;
import me.caofeng.enums.ResponseCode;
import me.caofeng.enums.Role;
import me.caofeng.pojo.Category;
import me.caofeng.pojo.Response;
import me.caofeng.service.api.ICategoryService;
import me.caofeng.util.CheckUtil;
import me.caofeng.util.Constant;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.net.InetAddress;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Copyright © 2017曹峰. All rights reserved.
 *
 * @Prject: mall
 * @Package: me.caofeng.service
 * @Description:
 * @Author: 曹峰 blog.caofeng.me
 * @Date: 2017-06-19 22:05
 * @Version: V1.0
 */
@Service
@Transactional
public class CategoryService implements ICategoryService {
    private static Logger LOGGER = LogManager.getLogger(CategoryService.class);

    @Autowired
    private CategoryMapper categoryMapper;

    private Cache<String, List<Category>> categoryCache = CacheBuilder
            .newBuilder()
            .expireAfterWrite(12, TimeUnit.HOURS)
            .build();

    @Override
    public Response<List<Category>> getCategories(Integer id, Integer status, Role role) {

        List<Category> categories = categoryMapper.getCategories(id, status, role.getId());
        if (null != categories && categories.size() > 0 ){
            return Response.response(ResponseCode.SUCCESS,"获取商品分类成功", categories);
        }else {
            return Response.response(ResponseCode.EMPTY, "获取商品分类成功", categories);
        }
    }

    @Override
    public Response<Category> getCategory(Integer parentId, Integer id, Integer status, Role role) {
        Category category = categoryMapper.getCategory(id, status, parentId, role.getId());
        if (null != category){
            return Response.response(ResponseCode.SUCCESS, "获取分类信息成功", category);
        }else {
            return Response.response(ResponseCode.EMPTY, "获取分类信息成功",null);
        }
    }

    @Override
    public Response<Category> addCategory(Category category) {

        Integer parentId = categoryMapper.isCategoryExists(category.getParentId());

        parentId = null == parentId ? 0 : parentId;
        category.setStatus(ItemStatus.ON);
        category.setParentId(parentId);

        try {
            int row = categoryMapper.addCategory(category);
            if (row != 1) {
                return Response.response(ResponseCode.ERROR, "添加分类失败", null);
            }
        } catch (Exception e) {
            LOGGER.error("分类节点已存在");
            LOGGER.error(e);
            return Response.response(ResponseCode.ERROR, "分类已经存在", null);
        }


        categoryCache.invalidate(Constant.CATEGORY + parentId);
        return Response.response(ResponseCode.SUCCESS, "ok", category);

    }

    @Override
    public Response<Category> deleteCategory(Integer id) {
        Category category = categoryMapper.getCategory(id, null, null, null);
        if (null == category) {
            return Response.response(ResponseCode.ILLEGAL_ARGUMENT, "分类不存在", null);
        }

        int row = categoryMapper.deleteCategory(id, ItemStatus.OFF);

        if (row != 1) {
            return Response.response(ResponseCode.ERROR, "删除分类失败", null);
        }
        categoryCache.invalidate(Constant.CATEGORY + category.getParentId() + Role.ADMIN);
        return Response.response(ResponseCode.SUCCESS, "删除分类成功", category);
    }

    @Override
    public Response<Category> updateCategoryName(Integer id, String name) {
        if (null == id || id < 0 || CheckUtil.isEmpty(name) || CheckUtil.isEmpty(name)) {
            return Response.response(ResponseCode.ILLEGAL_ARGUMENT, "分类名字不正确", null);
        }

        Response<Category> response = isCategoryExists(id);
        if (!response.isSuccess()) {
            return response;
        }

        int row = categoryMapper.updateCategory(id, name, null, null, null);
        if (row != 1) {
            return Response.response(ResponseCode.ERROR, "修改分类名字失败", null);
        }
        response.getData().setName(name);
        response.setMessage("修改分类名字成功");
        categoryCache.invalidateAll();
        return response;
    }

    @Override
    public Response<Category> updateCategoryParentId(Integer id, Integer parentId) {
        if (null == parentId || parentId < 0 || null == id || id <= 0 || id == parentId) {
            return Response.response(ResponseCode.ILLEGAL_ARGUMENT, "分类不存在", null);
        }

        if (parentId > 0) {
            Response parentExists = isCategoryExists(parentId);
            if (!parentExists.isSuccess()) {
                return parentExists;
            }
        }

        Response<Category> response = isCategoryExists(id);
        if (!response.isSuccess()) {
            return response;
        }

        int row = categoryMapper.updateCategory(id, null, null, parentId, null);

        if (row != 1) {
            return Response.response(ResponseCode.ERROR, "修改父分类失败", null);
        }

        response.getData().setParentId(parentId);
        response.setMessage("修改父分类成功");
        categoryCache.invalidateAll();
        return response;
    }

    @Override
    public Response<Category> updateCategoryStatus(Integer id, Integer status) {
        ItemStatus itemStatus = ItemStatus.getStatus(status);

        if (null == itemStatus || null == id) {
            return Response.response(ResponseCode.ILLEGAL_ARGUMENT, "分类不存在", null);
        }

        Response<Category> response = isCategoryExists(id);
        if (!response.isSuccess()) {
            return response;
        }

        int row = categoryMapper.updateCategory(id, null, itemStatus, null, null);

        if (row != 1) {
            return Response.response(ResponseCode.ERROR, "修改分类状态失败", null);
        }

        response.getData().setStatus(itemStatus);
        response.setMessage("修改分类状态成功");
        return response;
    }

    @Override
    public Response<Category> updateCategorySortOrder(Integer id, Integer sortOrder) {
        if (null == sortOrder || id == null) {
            return Response.response(ResponseCode.ILLEGAL_ARGUMENT, "分类不存在", null);
        }

        Response<Category> response = isCategoryExists(id);
        if (!response.isSuccess()) {
            return response;
        }

        int row = categoryMapper.updateCategory(id, null, null, null, sortOrder);

        if (row != 1) {
            return Response.response(ResponseCode.ERROR, "修改分类排序失败", null);
        }

        response.getData().setSortOrder(sortOrder);
        response.setMessage("修个分类排序成功");
        return response;
    }

    public Response<Category> isCategoryExists(Integer id) {
        Category category = categoryMapper.getCategory(id, null, null, null);
        if (null == category) {
            return Response.response(ResponseCode.ILLEGAL_ARGUMENT, "分类不能存在", null);
        }

        return Response.response(ResponseCode.SUCCESS, "分类存在", category);
    }


}
